package com.app.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.app.config.Settings;
import com.app.pojo.Status;
import com.app.utils.RedisUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

@Service
public class CaptchaService {
    private final JedisPool jedisPool;
    private Jedis jedis;
    private Jedis checkJedis(){
        if (!jedis.isConnected()||jedis.isBroken()){
            jedis.close();
            jedis=jedisPool.getResource();
            jedis.select(8);
            System.out.println(this+"---->刷新： "+jedis);
        }
        return jedis;
    }

    public CaptchaService(JedisPool jedisPool) {
        System.out.println("CaptchaService");
        this.jedisPool = jedisPool;
        jedis=jedisPool.getResource();
        jedis.select(8);
    }

    public LineCaptcha getCaptchaById(String id){
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(Settings.captchaWidth,Settings.captchaHigh);
        checkJedis().set(id,captcha.getCode(),new SetParams().ex(Settings.captcha_alive_second));
        System.out.println(id+" 获取新验证码："+captcha.getCode());
        return captcha;
    }

    /**
     * 检验验证码，不管通不通过，检验完成后验证码都会清除
     * @param id session ID
     * @param inputCode 用户输入的验证码
     * @return 0：通过，1：不通过，2：验证码失效
     */
    public boolean verifyCaptcha(String id,String inputCode){
        System.out.println(id+" 验证："+inputCode);
        return inputCode.equals(checkJedis().get(id));
    }
}
